/**
 * 
 */
package com.wolfpire.system.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wolfpire.system.common.Constants;
import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.EasyuiPagination;
import com.wolfpire.system.common.JsonHelper;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.Result;
import com.wolfpire.system.model.Attachment;
import com.wolfpire.system.service.AttachmentService;
import com.wolfpire.video.controller.ThreadPool;
import com.wolfpire.video.controller.VideoConverter;

/**
 * 附件控制器
 * @author lihd
 *
 */

@Controller
@RequestMapping("/attachment")
public class AttachmentController {
	
	private static final Pattern extPattern = Pattern.compile("doc|docx|xls|xlsx|txt|jpg|gif|png|rar|zip|tif|pdf|apk|ppt|pptx|pdm|apk|sql");
	private static final String POINT = ".";
	
	@Resource AttachmentService attachmentService;
	
	@ResponseBody
	@RequestMapping("/attachments")
	public List<Attachment> attachments(Long bizId, String attaType) {
		if (null != bizId) {
			return this.attachmentService.getByBiz(bizId, attaType);
		}
		return null;
	}
	
	@ResponseBody
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "moudle", required = false) String moudle,
			@RequestParam(value = "title", required = false) String title) {
		// TODO:
		try {
//			String rootPath = request.getSession().getServletContext().getRealPath("/");
			//rootPath = rootPath + ".." + File.separator;
			String rootPath = Constants.FILE_ROOT_PATH;
			if (!StringUtils.isBlank(moudle)) {
				moudle = "atta";
			}
			// 返回数据
			Attachment att = new Attachment();
		
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();//磁盘对象
				ServletFileUpload upload = new ServletFileUpload(factory);
				List<FileItem> items = upload.parseRequest(request);

				// 获取存储路径
				String tempPath =  moudle + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
				String savePath = rootPath + File.separator + "upload" + File.separator + tempPath;
				File saveDir = new File(savePath);
				if (!saveDir.exists()) {
					saveDir.mkdirs();
				}
				Iterator<FileItem> itr = items.iterator();
				String newFileName = null;
				while (itr.hasNext()) {
					FileItem item = itr.next();
					if ((!item.isFormField()) && (item.getName().length() > 0)) {
						String extName = FilenameUtils.getExtension(item.getName()).toLowerCase(Locale.ENGLISH);
						/*if(extName != null && !extName.equals("mp4")){
							return "{error:'未知异常！请检查文件大小、格式是否符合要求！'}";
						}*/
						//扩展名判断
					//	if(extPattern.matcher(extName).find()){
							newFileName = System.currentTimeMillis() + POINT + extName;
							att.setFileName(item.getName());
							att.setFileSize(String.valueOf(item.getSize()));
							att.setTitle((null != title) ? title : StringUtils.EMPTY);
							att.setFileType(extName);                   //标识附件的类型
							
							String filePath = savePath + File.separator + newFileName;
							File file = new File(filePath);
							item.write(file);
							//如果不是MP4和flv的格式  就要进行转码
							if(!"mp4".equals(extName)){
								String targetPath = filePath.substring(0, filePath.lastIndexOf("\\")+1);
								ThreadPool.trans(filePath, targetPath);
								//转码的文件都是flv格式的
								newFileName = newFileName.substring(0,newFileName.indexOf(".")) + ".mp4";
								
							}
							att.setFilePath("upload" + File.separator + tempPath + File.separator + newFileName);
							
							String path = Constants.FILE_ROOT_PATH + "\\" + "upload" + File.separator + tempPath + File.separator + newFileName;
							if("mp4".equals(extName)){         //如果是视频格式才进行第一张截图
								String imgPath = VideoConverter.processImg(path);
								att.setImgPath(imgPath.substring(imgPath.indexOf("upload\\")));
								att.setFileType(extName);                   //标识附件的类型
							}
							this.attachmentService.save(att);
					}
				}
//				response.getWriter().print(JsonHelper.getJsonString(att));
			}
			return JsonHelper.getJsonString(att);
		} catch (Exception e) {
			e.printStackTrace();
//			response.getWriter().print("{error:'未知异常！请检查文件大小、格式是否符合要求！'}");
//			return new Result(false, "上传文件格式不符合要求！");
			return "{error:'未知异常！请检查文件大小、格式是否符合要求！'}";
		}
	}
	
	@RequestMapping("/down")
	public String down(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "attId", required = false) Long attId) {
		// TODO:

		try {
			if(null != attId){
				Attachment attachment = this.attachmentService.get(attId);
//				String rootPath = request.getSession().getServletContext().getRealPath("/");
				//rootPath = "D:\\workflow-new" + File.separator;
				String rootPath = Constants.FILE_ROOT_PATH + File.separator;
				String allPath = rootPath + attachment.getFilePath();
				System.out.println("allPath============================"+allPath);
				// path是指欲下载的文件的路径。
				File file = new File(allPath);
//				String filename = file.getName();
//				String ext = filename.substring(filename.lastIndexOf(POINT) + 1);// .toUpperCase();
				String newfilename = attachment.getFileName();
//				String realName = attachment.getFileName();
//				realName = realName.substring(realName.lastIndexOf(POINT) + 1);
//				if (realName != null && !"".equals(realName))
//					newfilename = realName + POINT + ext;
				InputStream fis = new BufferedInputStream(new FileInputStream(allPath));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				// 设置response的Header
				response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(newfilename, "UTF-8"));
				response.addHeader("Content-Length", "" + file.length());
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
			}
		} catch(FileNotFoundException e){
			e.printStackTrace();
			System.out.println("---------文件下载失败，该文件不存在。-----------");
		}catch (IOException ex) {
			ex.printStackTrace();
			System.out.println("---------文件下载失败，该文件不存在。-----------");
		}
		
		return null;
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public Result delete(HttpServletRequest request,
			@RequestParam(value = "filePath") String filePath,
			@RequestParam(value = "attId", required = false) Long attId) {
		try {
			/*// 取工程根目录下
			String rootPath = request.getSession().getServletContext().getRealPath("/");*/
			if (StringUtils.isBlank(filePath)) {
				return new Result(true);
			}
			String rootPath = Constants.FILE_ROOT_PATH + File.separator;
			String allPath = rootPath+ filePath;
			File file = new File(allPath);
			if (file.exists()) {
				file.delete();
			}
			if (null != attId) {
				this.attachmentService.del(attId);
			}
			return new Result(true);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false);
		}
	}
	
	@ResponseBody
	@RequestMapping("/queryTaskDetailList")
	public EasyuiPagination<Map<String, Object>> queryTaskDetailList(EasyuiPage<Map<String, Object>>page, Attachment filterAttachment) {
		Page<Map<String, Object>> attachments = this.attachmentService.setTaskDetailList(page, filterAttachment);
		return new EasyuiPagination<Map<String, Object>>(attachments);
	}
	
	@ResponseBody
	@RequestMapping("/queryByPiId")
	public EasyuiPagination<Map<String, Object>> queryByPiId(
			EasyuiPage<Map<String, Object>> page,
			@RequestParam(value = "projectIndexId", required = false) Long projectIndexId,
			Attachment filterAttachment) {
		Page<Map<String, Object>> attachments = this.attachmentService.setAttachmentsByPiId(page, projectIndexId, filterAttachment);
		return new EasyuiPagination<Map<String, Object>>(attachments);
	}
	
	@ResponseBody
	@RequestMapping("/queryBySubjectId")
	public EasyuiPagination<Map<String, Object>> queryBySubjectId(
			EasyuiPage<Map<String, Object>> page,
			@RequestParam(value = "subjectId", required = false) Long subjectId,
			Attachment filterAttachment) {
		Page<Map<String, Object>> attachments = this.attachmentService.setAttachmentsBySubjectId(page, subjectId, null, filterAttachment);
		return new EasyuiPagination<Map<String, Object>>(attachments);
	}
}
